package com.lch.webdemo.wxhandler;

import com.lch.webdemo.wxservice.WeixinService;
import com.lch.webdemo.wxservice.builder.TextBuilder;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpKefuServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;


/**
 * @author liuchenhui
 */
@Component
@Slf4j
public class MsgHandler extends AbstractHandler {


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        // 回复消息
        String reply = "";
        // 如果回复的不是text,则不回复
        if (!"text".equals(wxMessage.getMsgType())) {
            return null;
        }
        WxMpKefuService kfService = new WxMpKefuServiceImpl(wxMpService);
        WeixinService weixinService = (WeixinService) wxMpService;
        try {
            String content = wxMessage.getContent();
            log.info("后台收到的消息是：" + content);
            WxMpUser user = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
            log.info("用户信息user={}", user);

            if (StringUtils.isBlank(content)) {
                return null;
            }
            // 选择将消息保存到本地
            if (("XXX").equals(content)) {
                reply = "XXX";
            }
            // 这里拿到了用户信息,需要更新互动用户的信息 以及 业务逻辑判断
            if (!StringUtils.isEmpty(reply)) {
                WxMpKefuMessage textMessage = WxMpKefuMessage.TEXT().content(reply).toUser(user.getOpenId()).build();
                kfService.sendKefuMessage(textMessage);
                return null;
            }
        } catch (WxErrorException e) {
            log.error("微信处理逻辑错误", e);
        } catch (Exception e) {
            log.error("服务器错误", e);
        }
        return new TextBuilder().build("自动回复", wxMessage, weixinService);
    }
}
